package com.fenghongzhang.day018;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private MediaPlayer mediaPlayer ;
    private SeekBar seekBar;

    private Timer timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = new MediaPlayer();


        new LinkedList<>();

        seekBar = (SeekBar) findViewById(R.id.seekBar);

        //拖动
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    public void start(View view) {
        Toast.makeText(this, "ddd", Toast.LENGTH_SHORT).show();
        //可以网址,可以是sd的路径
        try {
            //重置播放器的状态
            mediaPlayer.reset();
            ///storage/emulated/0/Music/Jam - 七月上.mp3

            /**
             * 1,上传完成以后 -> 重启
             * 2,通过sd的uri 读取所以的音频
             */
            mediaPlayer.setDataSource("http://m10.music.126.net/20200923155746/8a07e789e3d742bb33b7d8ca9644b067/ymusic/1766/43ab/d060/a517513f707a546a1cb14d708944b8ca.mp3");
//            mediaPlayer.prepare(); //同步
            //异步
            mediaPlayer.prepareAsync();
            //异步加载监听器
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                    seekBar.setMax(mediaPlayer.getDuration()); //最大值
                }
            });
            if(timer != null){
                timer.cancel();
            }
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                }
            },0,1000);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop(View view) {
        mediaPlayer.stop();
    }

    public void pause(View view) {
        mediaPlayer.pause();
    }

    public void restart(View view) {
        mediaPlayer.start();
    }
}
